<template>
  <view class="container">
    <!-- 扫码区域 -->
    <view class="scan-area">
      <view class="scan-frame">
        <view class="corner top-left"></view>
        <view class="corner top-right"></view>
        <view class="corner bottom-left"></view>
        <view class="corner bottom-right"></view>
      </view>
      
      <text class="scan-tip">将二维码放入框内即可自动扫描</text>
    </view>

    <!-- 手动输入 -->
    <view class="manual-input">
      <button class="input-btn" @click="showInputDialog">
        <text class="btn-icon">⌨️</text>
        <text class="btn-text">手动输入</text>
      </button>
    </view>

    <!-- 扫码历史 -->
    <view class="scan-history">
      <text class="history-title">最近扫描</text>
      <view v-if="scanHistory.length === 0" class="no-history">
        <text class="no-history-text">暂无扫描记录</text>
      </view>
      <view v-else class="history-list">
        <view 
          class="history-item" 
          v-for="(item, index) in scanHistory" 
          :key="index"
          @click="handleScanResult(item)"
        >
          <text class="history-content">{{ item.content }}</text>
          <text class="history-time">{{ formatTime(item.time) }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { scanQRCode } from '@/api/qrcode.js'

export default {
  data() {
    return {
      scanHistory: [] // 扫码历史
    }
  },
  onLoad() {
    this.loadScanHistory()
  },
  onShow() {
    // 页面显示时开始扫码
    this.startScan()
  },
  onHide() {
    // 页面隐藏时停止扫码
    this.stopScan()
  },
  methods: {
    // 开始扫码
    startScan() {
      // 这里应该调用相机扫码功能
      // 由于uni-app的扫码功能需要真机测试，这里先模拟
      console.log('开始扫码')
    },
    
    // 停止扫码
    stopScan() {
      console.log('停止扫码')
    },
    
    // 处理扫码结果
    async handleScanResult(result) {
      try {
        uni.showLoading({
          title: '解析中...'
        })
        
        // 调用扫码接口
        const res = await scanQRCode(result.content)
        
        uni.hideLoading()
        
        // 保存到历史记录
        this.saveToHistory(result.content)
        
        // 根据扫码结果跳转
        this.handleScanResponse(res.data)
        
      } catch (error) {
        uni.hideLoading()
        console.error('扫码失败:', error)
        uni.showToast({
          title: '扫码失败',
          icon: 'none'
        })
      }
    },
    
    // 处理扫码响应
    handleScanResponse(data) {
      const { type, merchantId, merchantName, action } = data
      
      switch (type) {
        case 'download':
          // 下载APP
          this.handleDownload()
          break
          
        case 'merchant':
          // 查看商家商品
          this.handleMerchant(merchantId, merchantName)
          break
          
        case 'checkout':
          // 结账
          this.handleCheckout()
          break
          
        default:
          uni.showToast({
            title: '未知的二维码类型',
            icon: 'none'
          })
      }
    },
    
    // 处理下载
    handleDownload() {
      uni.showModal({
        title: '下载APP',
        content: '是否跳转到APP下载页面？',
        success: (res) => {
          if (res.confirm) {
            // 跳转到下载页面
            uni.navigateTo({
              url: '/pages/download/download'
            })
          }
        }
      })
    },
    
    // 处理商家
    handleMerchant(merchantId, merchantName) {
      uni.showModal({
        title: '查看商家商品',
        content: `是否查看${merchantName}的商品？`,
        success: (res) => {
          if (res.confirm) {
            // 跳转到商家商品页面
            uni.navigateTo({
              url: `/pages/merchant/products?merchantId=${merchantId}`
            })
          }
        }
      })
    },
    
    // 处理结账
    handleCheckout() {
      uni.showModal({
        title: '结账',
        content: '是否进入结账页面？',
        success: (res) => {
          if (res.confirm) {
            // 跳转到结账页面
            uni.navigateTo({
              url: '/pages/checkout/checkout'
            })
          }
        }
      })
    },
    
    // 显示手动输入对话框
    showInputDialog() {
      uni.showModal({
        title: '手动输入',
        editable: true,
        placeholderText: '请输入二维码内容',
        success: (res) => {
          if (res.confirm && res.content) {
            this.handleScanResult({
              content: res.content,
              time: new Date().toISOString()
            })
          }
        }
      })
    },
    
    // 保存到历史记录
    saveToHistory(content) {
      const historyItem = {
        content: content,
        time: new Date().toISOString()
      }
      
      // 添加到历史记录开头
      this.scanHistory.unshift(historyItem)
      
      // 最多保存10条记录
      if (this.scanHistory.length > 10) {
        this.scanHistory = this.scanHistory.slice(0, 10)
      }
      
      // 保存到本地存储
      uni.setStorageSync('scanHistory', this.scanHistory)
    },
    
    // 加载扫码历史
    loadScanHistory() {
      const history = uni.getStorageSync('scanHistory')
      if (history) {
        this.scanHistory = history
      }
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) { // 1天内
        return Math.floor(diff / 3600000) + '小时前'
      } else {
        return date.toLocaleDateString()
      }
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #000;
  display: flex;
  flex-direction: column;
}

.scan-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
}

.scan-frame {
  width: 400rpx;
  height: 400rpx;
  position: relative;
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  border-radius: 20rpx;
}

.corner {
  position: absolute;
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #667eea;
}

.corner.top-left {
  top: -2rpx;
  left: -2rpx;
  border-right: none;
  border-bottom: none;
  border-top-left-radius: 20rpx;
}

.corner.top-right {
  top: -2rpx;
  right: -2rpx;
  border-left: none;
  border-bottom: none;
  border-top-right-radius: 20rpx;
}

.corner.bottom-left {
  bottom: -2rpx;
  left: -2rpx;
  border-right: none;
  border-top: none;
  border-bottom-left-radius: 20rpx;
}

.corner.bottom-right {
  bottom: -2rpx;
  right: -2rpx;
  border-left: none;
  border-top: none;
  border-bottom-right-radius: 20rpx;
}

.scan-tip {
  color: #fff;
  font-size: 28rpx;
  margin-top: 60rpx;
  text-align: center;
  opacity: 0.8;
}

.manual-input {
  padding: 40rpx;
  background: #fff;
}

.input-btn {
  width: 100%;
  height: 80rpx;
  background: #667eea;
  color: #fff;
  font-size: 28rpx;
  border-radius: 12rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-btn::after {
  border: none;
}

.btn-icon {
  font-size: 32rpx;
  margin-right: 15rpx;
}

.btn-text {
  font-size: 28rpx;
}

.scan-history {
  background: #fff;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.history-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
}

.no-history {
  text-align: center;
  padding: 60rpx 0;
}

.no-history-text {
  font-size: 28rpx;
  color: #999;
}

.history-list {
  max-height: 400rpx;
  overflow-y: auto;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.history-item:last-child {
  border-bottom: none;
}

.history-content {
  flex: 1;
  font-size: 26rpx;
  color: #333;
  margin-right: 20rpx;
  word-break: break-all;
}

.history-time {
  font-size: 22rpx;
  color: #999;
  white-space: nowrap;
}
</style>
